package com.scorpionstudio.girlstoryshop;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.scorpionstudio.girlstoryshop.adapter.LoadingAdapter;
import com.scorpionstudio.girlstoryshop.adapter.LoadingMoreListView;
import com.scorpionstudio.girlstoryshop.bean.DialogWarningNetwork;
import com.scorpionstudio.girlstoryshop.bean.ItemClothes;
import com.scorpionstudio.girlstoryshop.utils.JsonParser;
import com.scorpionstudio.girlstoryshop.utils.NetWork;
import com.scorpionstudio.girlstoryshop.utils.Variable;

public class LoadingScreenActivity extends ScorpionActivity {
    private static String TAG = "LoadingScreen";
    private LoadingMoreListView mList;
    private MyTask mTask = null;
    private ProgressDialog pDialog;
    private ItemClothes mClothes = new ItemClothes();
    private ArrayList<ItemClothes> mArrayListClothes = new ArrayList<ItemClothes>();
    private JSONArray mJsonArray = null;
    private int i = 1;
    private int positionList = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_loading_screen);
        mList = (LoadingMoreListView) findViewById(R.id.list_loading);
        try {
            loadData(Variable.LINK + i);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        mList.setOnLoadMoreListener(new LoadingMoreListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                i++;
                loadData(Variable.LINK + i);
                positionList += 10;
            }
        });

    }

    public void backMain(View v) {
        Intent mBackMain = new Intent(LoadingScreenActivity.this, MainSaleActivity.class);
        startActivity(mBackMain);
        finish();
    }

    @Override
    public void onBackPressed() {
        Intent mBackMain = new Intent(LoadingScreenActivity.this, MainSaleActivity.class);
        startActivity(mBackMain);
        finish();
    }

    private void loadData(String link) {
        try {
            if (NetWork.isOnline(getApplicationContext()) == true) {
                mTask = new MyTask();
                mTask.execute(link);
            } else {
                DialogWarningNetwork dialogWarningNetwork = new DialogWarningNetwork(LoadingScreenActivity.this) {
                    @Override
                    public void onYesClicked() {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
                        startActivity(intent);
                        finish();
                    }
                };
                dialogWarningNetwork.show();
            }


        } catch (Exception ex) {
            Log.e("error load", ex.toString());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public ArrayList<ItemClothes> getData(String url) {
        try {
            String json = JsonParser.getJSONString(url);
            JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
            mJsonArray = object.getJSONArray(Variable.ROOT_HOMEPAGE);
            for (int i = 0; i < mJsonArray.length(); i++) {
                JSONObject objJson = mJsonArray.getJSONObject(i);
                mClothes.setID(objJson.getInt(Variable.ID));
                mClothes.setUrlImg(objJson.getString(Variable.IMAGE));
                mClothes.setDescriptionImg(objJson.getString(Variable.NAME));
                mClothes.setCostItems(objJson.getString(Variable.COST));
                mClothes.setDetail(objJson.getString(Variable.DETAILS));
                mArrayListClothes.add(mClothes);
                mClothes = new ItemClothes();
            }
        } catch (Exception e) {
            Log.e("load data", "json " + e.toString());
        }
        return mArrayListClothes;
    }

    private class MyTask extends AsyncTask<String, Void, ArrayList<ItemClothes>> {
        @Override
        protected void onPreExecute() {
            if (i == 1) {
                pDialog = new ProgressDialog(LoadingScreenActivity.this);
                pDialog.setMessage("Tải dữ liệu..");
                pDialog.setCancelable(true);
                pDialog.setCanceledOnTouchOutside(false);
                pDialog.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        mList.onLoadMoreComplete();
                        cancel(true);
                    }
                });
                pDialog.show();
            }
        }

        @Override
        protected ArrayList<ItemClothes> doInBackground(String... params) {
            ArrayList<ItemClothes> arrayResult = getData(params[0]);
            Log.e(TAG, params[0]);
            if (null != arrayResult && arrayResult.size() > 0) {
                publishProgress();

            }
            return arrayResult;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            //mTextView.setText(itemsMusic.get(0).getName());
        }

        @Override
        protected void onPostExecute(ArrayList<ItemClothes> result) {
            Log.e("count item :", "" + result.size());
            if (null != pDialog && pDialog.isShowing()) {
                mTask.cancel(true);
                pDialog.cancel();
                pDialog.dismiss();
            }
            if (result != null && result.size() > 0) {
                LoadingAdapter mAdapter = new LoadingAdapter(LoadingScreenActivity.this, android.R.layout.simple_list_item_1, mArrayListClothes);
                mList.setAdapter(mAdapter);
                mList.onLoadMoreComplete();
                mList.setSelection(positionList);
                mAdapter.notifyDataSetChanged();
            } else {
                AlertDialog.Builder mAlert = new AlertDialog.Builder(
                        LoadingScreenActivity.this);
                mAlert.setTitle("Không có dữ liệu");
                mAlert.setMessage(
                        "Đã có lỗi trong quá trình tải, Bạn có muốn tải lại không ?")
                        .setPositiveButton("Có",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        try {
                                            mTask = new MyTask();
                                            mTask.execute(Variable.LINK);
                                        } catch (Exception ex) {
                                            Log.e("error load", ex.toString());
                                        }
                                    }
                                })
                        .setNegativeButton("Không",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.cancel();
                                        dialog.dismiss();
//	                                        pDialog.cancel();
//	                                        pDialog.dismiss();
                                        mTask.cancel(true);
                                        finish();
                                    }
                                });
                AlertDialog mAlertDialog = mAlert.create();
                mAlertDialog.show();
            }
        }
    }
}
